// 获取dom元素
let localVideo = document.getElementById('localVideo');
let remoteVideo = document.getElementById('remoteVideo');

let btnStart = document.getElementById('start');
let btnCall = document.getElementById('call');
let btnHangup = document.getElementById('hangup');

let offer = document.getElementById('offerSdp');
let answer = document.getElementById('answerSdp');

let localStream;
let pc1;
let pc2;

function getMediaStream(mediaStream) {
    localVideo.srcObject = mediaStream;
    localStream = mediaStream;
}

function handleError(err) {
    console.log('getUserMedia error:', err);
}

function start() {
    if(!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        console.log('getUserMedia is not supported!');
        return;
    } else {
        let constraints = {
            video: true,
            audio: false
        }
        navigator.mediaDevices.getUserMedia(constraints)
            .then(getMediaStream)
            .catch(handleError);
    }

}

function getRemoteStream(e) {
    remoteVideo.srcObject = e.streams[0];
}

function handleOfferError(err) {
    console.log('createOffer error:', err);
}

function handleAnswerError(err) {
    console.log('createAnswer error:', err);
}

function getOffer(desc) {
    pc1.setLocalDescription(desc);
    offer.value = desc.sdp;

    pc2.setRemoteDescription(desc);

    pc2.createAnswer()
        .then(getAnswer)
        .catch(handleAnswerError);
}

function getAnswer(desc) {
    pc2.setLocalDescription(desc);
    answer.value = desc.sdp;
    pc1.setRemoteDescription(desc);
}

function call() {
    pc1 = new RTCPeerConnection();
    pc2 = new RTCPeerConnection();
    pc1.onicecandidate = (e) => {
        pc2.addIceCandidate(e.candidate);
    }
    pc2.onicecandidate = (e) => {
        pc1.addIceCandidate(e.candidate);
    }

    pc2.ontrack = getRemoteStream;

    localStream.getTracks().forEach(track => {
        pc1.addTrack(track, localStream);
    });

    let offerOptions = {
        offerToReceiveAudio: 0,
        offerToReceiveVideo: 1
    }
    pc1.createOffer(offerOptions)
        .then(getOffer)
        .catch(handleOfferError);
}

function hangup() {
    pc1.close();
    pc2.close();
    pc1 = null;
    pc2 = null;
}

btnStart.onclick = start;
btnCall.onclick = call;
btnHangup.onclick = hangup;